<!-- 样本文件管理 -->
<template>
  <!-- <el-dialog @close="closeHandler" v-model="maskObj.flag" title="预览">
    <span style="display:inline-block;width:200px;font-size: 20px;">样本数量: {{ lineCount }}</span>
    <iframe id="fileFrame" sandbox="allow-scripts allow-top-navigation allow-same-origin allow-popups" 
      :src="maskObj.url"  
      frameborder="0"
      style=" z-index: 1000;height:560px;width:100%">
    </iframe>
  </el-dialog> -->
  <div v-loading.fullscreen.lock="fullscreenLoading">
    <!-- 图片预览 -->
    <el-image-viewer v-if="showImageViewer" :url-list="[url]" @close="close" />
    <el-dialog @close="closeHandler" v-model="maskObj.flag" title="预览">
      <span style="display: inline-block; width: 200px; font-size: 20px"
        >样本数量: {{ lineCount }}</span
      >
      <iframe
        id="fileFrame"
        sandbox="allow-scripts allow-top-navigation allow-same-origin allow-popups"
        :src="maskObj.url"
        frameborder="0"
        style="z-index: 1000; height: 560px; width: 100%"
      >
      </iframe>
    </el-dialog>
    <div class="gva-table-box">
      <warning-bar
        v-if="urlPath == 'File'"
        title="点击“文件名称”或者“文件备注”可以编辑对应对容,点击权限可以更改文件权限"
      />
      <warning-bar
        v-if="urlPath == 'Backup'"
        title="备份文件为分批备份，若需要特定时间文件，请下载特定时间备份文件的所有部分"
      />
      <div class="gva-btn-list">
        <upload-common
          v-if="urlPath == 'File'"
          :key="uploadKey"
          :dir="route.query.dir"
          class="upload-btn"
          @on-success="refresh"
        />
        <el-button
          v-if="urlPath == 'File' || urlPath == 'Backup'"
          class="upload-btn"
          type="primary"
          @click="batchDownloadFile()"
          >批量下载</el-button
        >
        <el-button
          v-if="urlPath == 'File'"
          class="upload-btn"
          type="primary"
          @click="createFolder()"
          >新建文件夹</el-button
        >
        <el-form ref="searchForm" :inline="true" :model="search">
          <el-form-item label="">
            <el-input
              v-model="search.keyword"
              class="keyword"
              :placeholder="
                '请输入' + (urlPath != 'Dir' ? '文件名称' : '文件夹名称')
              "
              @input="refresh"
            />
          </el-form-item>
          <!-- =====================以下为新增根据标签/文件类型查询=============================== -->
          <el-form-item
            label="文件类型"
            prop="tag"
            v-if="urlPath != 'Dir' && urlPath != 'Backup'"
          >
            <el-select
              v-model="search.tag"
              clearable
              placeholder="请选择"
              @change="refresh"
              @clear="
                () => {
                  search.tag = undefined;
                }
              "
              style="width: 150px"
            >
              <el-option
                v-for="(item, key) in tag_attributeOptions"
                :key="key"
                :label="item.label"
                :value="item.value"
              />
              <!-- <el-option label="jpg" value="jpg"></el-option>>
              <el-option label="png" value="png"></el-option>>
              <el-option label="xls" value="xls"></el-option>>
              <el-option label="pdf" value="pdf"></el-option>>
              <el-option label="txt" value="txt"></el-option>> -->
            </el-select>
          </el-form-item>

          <el-form-item label="" v-if="urlPath != 'Backup'">
            <el-input
              v-model="search.creator"
              class="creator"
              :placeholder="
                '请输入' + (urlPath == 'File' ? '上传用户' : '创建用户')
              "
              @input="refresh"
            />
          </el-form-item>

          <el-form-item>
            <el-date-picker
              v-model="search.time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="refresh"
            >
            </el-date-picker>
          </el-form-item>
          <!-- =====================以上为新增根据标签/文件类型查询=============================== -->
          <!-- <el-form-item>
            <el-button type="primary" icon="search" @click="refresh"
              >查询</el-button
            >
          </el-form-item> -->
        </el-form>
      </div>
      <div v-if="urlPath != 'Backup'">
        <div class="gva-crumb" v-if="!globalSearch">
          <!-- 文件夹选择 -->
          <el-form :inline="true" :model="dirQuery">
            <el-form-item>
              <!-- 文件夹显示 -->
              <el-breadcrumb :separator-icon="ArrowRight">
                <el-breadcrumb-item
                  v-for="(item, index) in fileDir"
                  :key="index"
                >
                  <el-link
                    :underline="false"
                    @click="handleCrumbClick(item, index)"
                  >
                    {{ item }}
                  </el-link>
                </el-breadcrumb-item>
              </el-breadcrumb>
            </el-form-item>
            <!-- <el-form-item>
              <el-select
                v-model="dirQuery.dir"
                clearable
                placeholder="请选择"
                @change="changeDir"
                @clear="
                  () => {
                    dirQuery.dir = undefined;
                  }
                "
                style="width: 150px"
              >
                <el-option
                  v-if="shouldShow"
                  key=".."
                  label="上一级"
                  value=".."
                />
                <el-option
                  v-for="dir in dirList"
                  :key="dir"
                  :label="dir"
                  :value="dir"
                />
              </el-select>
            </el-form-item> -->
          </el-form>
        </div>
        <div v-else style="margin-bottom: 10px">
          <el-tag
            closable
            type="primary"
            @close="
              search.keyword = null;
              search.creator = null;
              search.time = null;
              search.tag = null;
              refresh();
            "
          >
            当前文件夹"{{ route.query.dir }}" 及子文件夹搜索结果
          </el-tag>
        </div>
      </div>
      <!-- 表内容 -->
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column align="left" label="预览" width="100">
          <template #default="scope">
            <CustomPic
              pic-type="file"
              :pic-src=getScopeRowUrl(scope.row)
              @click="showImg(scope.row.url)"
            />
          </template>
        </el-table-column> -->
        <el-table-column
          v-if="urlPath != 'Dir'"
          type="selection"
          width="55"
          :selectable="selectable"
        />
        <el-table-column align="left" label="名称" prop="name" min-width="300">
          <template #default="scope">
            <div
              v-if="urlPath == 'File' && scope.row.tag == 'dir'"
              class="name blue-underline"
            >
              <a
                :href="constructHref(scope.row)"
                @click.prevent="navigateToDir(scope.row)"
                class="blue-underline"
                >{{ scope.row.name }}</a
              >
            </div>
            <div
              v-else-if="scope.row.tag != 'dir'"
              class="name"
              @click="editFileNameFunc(scope.row)"
            >
              {{ scope.row.name }}
            </div>
            <div v-else>
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="urlPath != 'Backup'"
          align="left"
          :label="urlPath != 'Dir' ? '文件地址' : '地址'"
          prop="logicAddress"
          min-width="300"
        >
          <template #default="scope">
            <div class="logicAddress">
              {{ scope.row.logicAddress }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          align="left"
          label="文件大小"
          prop="fileSize"
          min-width="150"
        >
          <template #default="scope">
            <div class="fileSize">
              {{ formatFileSize(scope.row.fileSize) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          v-if="urlPath != 'Dir'"
          align="left"
          label="文件类型"
          prop="tag"
          min-width="100"
        >
          <template #default="scope">
            <el-tag
              :type="scope.row.tag === 'jpg' ? 'primary' : 'success'"
              disable-transitions
              >{{ scope.row.tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="urlPath == 'File'"
          align="left"
          label="文件权限"
          prop="tag"
          min-width="100"
        >
          <template #default="scope">
            <div
              class="name"
              @click="changePermissionFunc(scope.row)"
              v-if="scope.row.tag != 'dir'"
            >
              {{ scope.row.permission ? "公开" : "私有" }}
            </div>
            <div class="name" v-else></div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="urlPath != 'Backup'"
          align="left"
          :label="urlPath == 'File' ? '上传用户' : '创建用户'"
          prop="tag"
          width="100"
        >
          <template #default="scope">
            <div class="name">
              {{ scope.row.creator }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          align="left"
          :label="urlPath == 'File' ? '上传日期' : '创建日期'"
          prop="CreatedAt"
          min-width="180"
        >
          <template #default="scope">
            <div>{{ formatDate(scope.row.CreatedAt) }}</div>
          </template>
        </el-table-column>

        <el-table-column
          v-if="urlPath == 'File'"
          align="left"
          label="文件备注"
          prop="desc"
          min-width="300"
        >
          <template #default="scope">
            <div
              class="name"
              @click="editFileDescFunc(scope.row)"
              v-if="scope.row.tag != 'dir'"
            >
              {{ scope.row.desc || "备注为空，点击编辑备注" }}
            </div>
            <div v-else></div>
          </template>
        </el-table-column>

        <el-table-column align="left" label="操作" min-width="200">
          <template #default="scope">
            <el-button
              v-if="urlPath == 'File' && scope.row.tag != 'dir'"
              size="small"
              icon="download"
              type="primary"
              link
              @click="show(scope.row)"
              :disabled="disablePreview(scope.row)"
              >预览</el-button
            >
            <el-button
              v-if="scope.row.key != '..'"
              size="small"
              icon="download"
              type="primary"
              link
              @click="downloadFile(scope.row)"
              >下载</el-button
            >
            <el-button
              v-if="urlPath != 'Backup' && scope.row.key != '..'"
              size="small"
              icon="delete"
              type="primary"
              link
              @click="confirmDelPassword(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>

        <el-table-column align="center" label="下载列表" min-width="200">
          <template #default="scope">
            <div style="height: 100%; margin-top: 13px">
              <el-progress
                v-if="urlPath != 'Dir' && scope.row.tag != 'dir'"
                :color="customColors"
                :percentage="scope.row.downloadProgress"
              ></el-progress>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :style="{ float: 'right', padding: '20px' }"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <!-- 权限提示框 -->
    <el-dialog v-model="dialogVisible" title="Tips" width="500">
      <span>This is a message</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getFileList,
  deleteFile,
  editFileName,
  editFileDesc,
  getImg,
  changePermission,
  newFolder,
  getDirList,
  getAllFileByDir,
  getBackupFileCount
} from "@/api/fileUploadAndDownload";
import { confirmPassword } from "@/api/user";
import { getFileLineCount } from "@/api/sampleData";

import { downloadOtherFile } from "@/utils/downloadImg";
import UploadCommon from "@/components/upload/common.vue";
import { formatDate } from "@/utils/format";
import WarningBar from "@/components/warningBar/warningBar.vue";
import { useUserStore } from "@/pinia/modules/user";
import {
  ref,
  watch,
  shallowReactive,
  onUnmounted,
  onActivated,
  computed,
} from "vue";
import { ArrowRight } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import { useRoute, useRouter } from "vue-router";
const updData = ref([]);
const path = ref(import.meta.env.VITE_BASE_API);
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const search = ref({});
const tableData = ref([]);
const customColors = ref([
  { color: "#f56c6c", percentage: 20 },
  { color: "#e6a23c", percentage: 40 },
  { color: "#5cb87a", percentage: 60 },
  { color: "#1989fa", percentage: 80 },
  { color: "#6f7ad3", percentage: 100 },
]);
const userStore = useUserStore();
const multipleTableRef = ref();
// 获取url参数
const route = useRoute();
const router = useRouter();
const tag_attributeOptions = [
  { label: "txt", value: "txt" },
  { label: "bmp/jpg/png/tif/svg", value: "tp" },
  { label: "xls/xlsx", value: "xls" },
  { label: "doc/docx", value: "wd" },
  { label: "ppt/pptx", value: "ppt" },
  { label: "pdf", value: "pdf" },
  { label: "rar/zip/7z", value: "zip" },
  { label: "exe", value: "exe" },
  { label: "其他", value: "else" },
];
const refreshUrl = () => {
  const currentQuery = { ...route.query };
  currentQuery.dir = "/";
  router.replace({
    path: route.path,
    query: currentQuery,
  });
};
const globalSearch = ref(
  computed(
    () =>
      !!(
        search.value?.keyword ||
        search.value?.creator ||
        search.value?.time ||
        search.value?.tag
      ) ?? ""
  )
);

// 文件大小格式化函数
const formatFileSize = (size) => {
  console.log(size);
  if (size == null) return "";
  if (size == "") return "";
  if (size == "0") return "0B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  const i = Math.floor(Math.log(size) / Math.log(k));
  return `${(size / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
};

//日期对象转换为字符串函数
const timeToString = (timeObj) => {
  if (timeObj == null) {
    return "";
  }
  var str = " ";
  var year = timeObj.getFullYear();
  var month = timeObj.getMonth() + 1;
  var date = timeObj.getDate();
  // var time = timeObj.toTimeString().split(" ")[0];
  // var rex = new RegExp(/:/g);
  str = year + "-" + month + "-" + date;
  console.log(str);
  return str;
};

// 查询getTableData
const getTableData = async () => {
  const path = urlPath.value;
  var startTime = "";
  var endTime = "";
  if (search.value.time != null && search.value.time.length == 2) {
    if (timeToString(search.value.time[0]) != "") {
      startTime = timeToString(search.value.time[0]) + " 00:00:00";
    }

    endTime = timeToString(search.value.time[1]) + " 23:59:59";
  }
  if (!route.query.dir) {
    refreshUrl();
    return;
  }
  let param = {
    page: page.value,
    pageSize: pageSize.value,
    dir: route.query.dir,
    authorityId: userStore.userInfo.authorityId,
    userName: userStore.userInfo.userName,
    globalSearch: globalSearch.value,
    urlPath: path,
    startTime: startTime,
    endTime: endTime,
    ...search.value,
  };
  const table = await getFileList(param);
  if (table.code === 0) {
    if (route.query.dir != "/") {
      let preDir = {
        CreatedAt: "2024-10-07T19:11:17.870701+08:00",
        ID: -1,
        UpdatedAt: "2024-10-07T19:11:17.870701+08:00",
        creator: "admin",
        desc: "",
        key: "..",
        logicAddress: route.query.dir,
        name: "上一级文件夹",
        permission: false,
        tag: "dir",
        url: "dir",
      };
      // 开头新加入一个对象
      table.data.list.unshift(preDir);
    }
    tableData.value = table.data.list;
    total.value = table.data.total;
    page.value = table.data.page;
    pageSize.value = table.data.pageSize;
  }
};
// 批量下载
const handleSelectionChange = (rows) => {
  updData.value = rows;
};
const clearTableSelection = () => {
  if (multipleTableRef.value) {
    multipleTableRef.value.clearSelection();
  }
};
const batchDownloadFile = () => {
  if (!updData.value || updData.value.length == 0) {
    ElMessage({
      message: "下载文件为空，请先勾选",
      type: "warning",
    });
    return;
  }
  updData.value.forEach((element) => {
    downloadFile(element);
  });
  clearTableSelection();
};
// 获取url的最后一段
const urlPath = ref(
  computed(() => {
    console.log("urlPath" + route.path.split("/").pop());
    return route.path.split("/").pop();
  })
);
// 文件夹
const dirQuery = ref({});
const fileDir = ref([]);
const shouldShow = ref(computed(() => route.query.dir != "/"));
// 监听路由变化
watch(
  () => route.query.dir,
  (dir) => {
    updateFileDir(dir);
  }
);
watch(
  () => route.query,
  () => {
    if (
      urlPath.value == "File" ||
      urlPath.value == "Dir" ||
      urlPath.value == "Backup"
    ) {
      refresh();
    }
  }
);
const updateFileDir = (dir) => {
  // 初始化 fileDir.value 为一个只包含 "全部文件" 的数组
  fileDir.value = ["根路径"];
  if (!dir || dir === "/") {
    // 如果 dir 为空或者是根目录 "/"，我们只保留 "全部文件"
    return;
  }
  // 移除开头的 "/" （如果存在）
  const trimmedDir = dir.startsWith("/") ? dir.slice(1) : dir;
  // 按照斜杠分割路径，并过滤掉空字符串
  const dirParts = trimmedDir.split("/").filter((part) => part !== "");
  // 将分割后的路径部分添加到 fileDir.value 中
  fileDir.value.push(...dirParts);
};
updateFileDir(route.query.dir);
const changeDir = () => {
  if (!dirQuery.value.dir) {
    refreshUrl();
    return;
  }
  const currentQuery = { ...route.query };
  if (dirQuery.value.dir == "..") {
    // 删除最后一个斜杠及其后面的所有字符
    currentQuery.dir = currentQuery.dir.replace(/\/[^/]*$/, "");
    // 如果删除后为空字符串，则删除 dir 参数
    if (currentQuery.dir == "") {
      currentQuery.dir = "/";
    }
  } else {
    if (currentQuery.dir != "/") {
      currentQuery.dir += "/";
    }
    console.log(dirQuery.value.dir);
    currentQuery.dir += dirQuery.value.dir;
  }
  router.replace({
    path: route.path,
    query: currentQuery,
  });
  dirQuery.value.dir = undefined;
};
// 点击文件夹路径执行函数
const handleCrumbClick = (item, index) => {
  const currentQuery = { ...route.query };
  if (index == 0) {
    currentQuery.dir = "/";
  } else {
    // 构建新的 dir 路径
    const newPath = route.query.dir
      .split("/")
      .slice(0, index + 1)
      .join("/");
    currentQuery.dir = newPath || "/";
  }
  router.replace({
    path: route.path,
    query: currentQuery,
  });
};
// 新建文件夹
const createFolder = async () => {
  ElMessageBox.prompt("请输入文件夹名", "新建文件夹", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /\S/,
    inputErrorMessage: "不能为空",
  })
    .then(async ({ value }) => {
      if (!isValidFolderName(value)) {
        console.log(value);
        return;
      }
      let param = {
        dirName: route.query.dir,
        name: value,
        userName: userStore.userInfo.userName,
        permission: false,
      };
      const res = await newFolder(param);
      if (res.code === 0) {
        ElMessage({
          type: "success",
          message: "新建文件夹成功!",
        });
        refresh();
      }
    })
    .catch((e) => {
      console.log(e);
      ElMessage({
        type: "info",
        message: "取消修改",
      });
    });
};
const dirList = ref([]);
const getDirListFunc = async () => {
  let param = {
    dirName: route.query.dir,
    userName: userStore.userInfo.userName,
  };
  const res = await getDirList(param);
  if (res.code === 0) {
    dirList.value = res.data;
  }
};
const uploadKey = ref(0);
const refresh = () => {
  console.log("refresh");
  getDirListFunc();
  getTableData();
  uploadKey.value += 1;
};
refresh();
const isValidFolderName = (folderName) => {
  // 1. 检查长度（例如：1到255个字符）
  if (folderName.length < 1 || folderName.length > 255) {
    ElMessage({
      message: "文件夹名称长度必须在1到255个字符之间。",
      type: "error",
    });
    return false;
  }
  // 2. 检查是否包含非法字符
  const illegalChars = /[<>:"/\\|?*\x00-\x1F]/;
  if (illegalChars.test(folderName)) {
    ElMessage({
      message: '文件夹名称包含非法字符（< > : " / \\ | ? * 或控制字符）。',
      type: "error",
    });
    return false;
  }
  // 3. 检查是否以点(.)或空格结尾
  if (folderName.endsWith(".") || folderName.endsWith(" ")) {
    ElMessage({
      message: "文件夹名称不能以点(.)或空格结尾。",
      type: "error",
    });
    return false;
  }
  // 4. 检查是否以空格开头
  if (folderName.startsWith(" ")) {
    ElMessage({
      message: "文件夹不能以空格开头",
      type: "error",
    });
    return false;
  }
  // 如果通过了所有检查，则返回有效
  return true;
};
// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  refresh();
};
const handleCurrentChange = (val) => {
  page.value = val;
  refresh();
};

const delFile = async (row) => {};

const delDir = async () => {};

const confirmDelPassword = async (row) => {
  ElMessageBox.prompt("请输入删除密码", "删除密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /\S/,
    inputErrorMessage: "不能为空",
    inputType: "password",
  })
    .then(async ({ value }) => {
      let param = {
        delPassword: value,
      };
      const res = await confirmPassword(param);
      if (res.code === 0) {
        ElMessage({
          type: "success",
          message: "密码正确!",
        });
        deleteFileFunc(row);
        refresh();
      }
    })
    .catch((e) => {
      console.log(e);
      ElMessage({
        type: "info",
        message: "取消修改",
      });
    });
};

const deleteFileFunc = async (row) => {
  ElMessageBox.confirm("此操作将永久删除文件, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteFile(row, userStore.userInfo.userName);
      if (res.code === 0) {
        ElMessage({
          type: "success",
          message: "删除成功!",
        });
        if (tableData.value.length === 1 && page.value > 1) {
          page.value--;
        }
        refresh();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
const downloadFile = async (row) => {
  // if (row.url.indexOf("http://") > -1 || row.url.indexOf("https://") > -1) {
  //   console.log("下载地址: %s", row.url);
  //   downloadImage(row.url, row.name);
  // } else {
  //   debugger;
  //   downloadImage(path.value + "/" + row.url, row.name);
  // }
  // row.downloadProgress = 0;
  // tableData.value.push(row);
  // =================================以下为文件下载========================
  console.log(row);
  if (row.tag == "dir") {
    let dir = row.logicAddress;
    if (dir != "/") {
      dir += "/";
    }
    dir = dir + row.name;
    console.log(userStore.userInfo.userName);
    let res = await getAllFileByDir(dir, userStore.userInfo.userName);
    console.log(res.data);
    res.data.forEach(async (item, index) => {
      let r = {
        tag: item.tag,
        url: item.url,
        name: item.name,
      };
      await downloadFile(r);
    });
  } else if (row.tag == "jpg" || row.tag == "png" || row.tag == "jpeg") {
    console.log(row.url + "/" + row.name);
    await fetchImage(row.url, row.name, row.tag);
  } else {
    console.log(row.url);
    if (urlPath.value == "Backup") {
      console.log(row.name.slice(0,17));
      let res = await getBackupFileCount(row.name.slice(0,17));
      console.log(res.data);
      if (res.data > 0) {
        ElMessage.warning("该备份文件共有" + res.data + "个部分，当前为第" + row.name.slice(20, 21) + "部分");
      }
    }
    downloadOtherFile1(row);
  }
};

const downloadOtherFile1 = (row) => {
  let fileSrc = row.url;
  let name = row.name;

  //下载其它类型的文件

  let xhr = new XMLHttpRequest();
  ElMessage.success("开始下载");

  xhr.open(
    "GET",
    `/api/download?fileSrc=${encodeURIComponent(
      fileSrc
    )}&name=${encodeURIComponent(name)}`,
    true
  );
  // xhr.setRequestHeader("Range", "bytes=" + start + "-");
  xhr.responseType = "blob";

  xhr.onprogress = function (event) {
    if (event.lengthComputable) {
      // 更新进度条状态
      row.downloadProgress = (event.loaded / event.total) * 100;
      row.downloadProgress = Math.round(row.downloadProgress);
    }
  };

  xhr.onload = function () {
    var blob = new Blob([xhr.response], { type: "application/octet-stream" });
    var downloadUrl = URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.href = downloadUrl;
    a.download = name || "file";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(downloadUrl);
    ElMessage.success("下载完成");
    // 下载完成后重置进度条状态
    row.downloadProgress = 0;
  };
  xhr.send();
};

/**
 * 编辑文件名或者备注
 * @param row
 * @returns {Promise<void>}
 */
const editFileNameFunc = async (row) => {
  ElMessageBox.prompt(
    "请输入" + (urlPath == "File" ? "文件名称" : "文件夹名"),
    "编辑",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /\S/,
      inputErrorMessage: "不能为空",
      inputValue: row.name,
    }
  )
    .then(async ({ value }) => {
      row.name = value;
      const res = await editFileName(row);
      if (res.code === 0) {
        ElMessage({
          type: "success",
          message: "编辑成功!",
        });
        refresh();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消修改",
      });
    });
};

/**
 * 编辑文件名或者备注
 * @param row
 * @returns {Promise<void>}
 */
const editFileDescFunc = async (row) => {
  if (
    userStore.userInfo.userName !== "admin" &&
    row.creator !== userStore.userInfo.userName
  ) {
    ElMessage.error("只能修改自己的文件备注");
    return;
  }
  ElMessageBox.prompt("请输入文件备注", "编辑", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    // inputPattern: /\S/,
    // inputErrorMessage: "不能为空",
    inputValue: row.desc || "",
  })
    .then(async ({ value }) => {
      row.desc = value;
      // console.log(row)
      const res = await editFileDesc(row);
      if (res.code === 0) {
        ElMessage({
          type: "success",
          message: "编辑成功!",
        });
        getTableData();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消修改",
      });
    });
};

// 更改权限
const changePermissionFunc = async (row) => {
  if (row.creator !== userStore.userInfo.userName) {
    ElMessage.error("只能修改自己的权限");
    return;
  }

  ElMessageBox.confirm(
    "确定要修改权限为 " + (row.permission ? "私有" : "公开") + " 吗？",
    "编辑",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }
  )
    .then(async () => {
      // 深拷贝避免闪回问题
      const data = JSON.parse(JSON.stringify(row));
      data.permission = !data.permission;
      const res = await changePermission(data);
      if (res.code === 0) {
        ElMessage({
          type: "success",
          message: "修改成功!",
        });
        refresh();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消修改",
      });
    });
};
// 对话框组件
const dialogVisible = ref(false);
// 从预览图片中下载图片
// 下载图片的函数
const downloadImage = (imageData, fileName) => {
  const byteString = atob(imageData.split(",")[1]);
  const mimeString = imageData.split(",")[0].split(":")[1].split(";")[0];
  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  const blob = new Blob([ab], { type: mimeString });

  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = fileName;

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  URL.revokeObjectURL(link.href);
};
// 获取图片数据的函数
const fetchImage = async (url, name, tag) => {
  try {
    const resp = await getImg(url);
    let imageData;
    if (tag === "jpeg" || tag === "jpg") {
      imageData = `data:image/jpeg;base64,${resp.data}`;
    } else if (tag === "png") {
      imageData = `data:image/png;base64,${resp.data}`;
    } else {
      console.error("Unsupported image type");
      return;
    }
    downloadImage(imageData, name);
  } catch (error) {
    console.error("Error fetching image:", error);
  }
};
const constructHref = (row) => {
  const dirName = row.name;
  const currentPath = route.path;
  const currentDir = route.query.dir || "";
  let newDir;
  if (row.key != "..") {
    newDir =
      currentDir === "/"
        ? `${currentDir}${dirName}`
        : `${currentDir}/${dirName}`;
  } else {
    // 处理返回上一级的情况
    const dirs = currentDir.split("/").filter(Boolean); // 分割路径并移除空字符串
    dirs.pop(); // 移除最后一个目录
    newDir = dirs.length > 0 ? "/" + dirs.join("/") : "/";
  }
  return `${currentPath}?dir=${newDir}`;
};

const navigateToDir = (row) => {
  const newPath = constructHref(row);
  router.push(newPath);
};

const selectable = (row, index) => {
  return row.tag != "dir";
};
</script>

<script>
// 预览置灰
const disablePreview = (row) => {
  return (
    row.tag !== "txt" &&
    row.tag !== "bmp" &&
    row.tag !== "jpg" &&
    row.tag !== "png" &&
    row.tag !== "tif" &&
    row.tag !== "svg" &&
    row.tag !== "jpeg"
  );
};

const showImageViewer = ref(false); //组件是否显示
const url = ref([]); //预览大图的路径集合
// 预览大图
const showImg = async (row) => {
  try {
    const resp = await getImg(row.url);
    var imageData;
    if (row.tag == "jpeg") {
      imageData = `data:image/jpeg;base64,${resp.data}`;
    } else if (row.tag == "png") {
      imageData = `data:image/png;base64,${resp.data}`;
    } else if (row.tag == "jpg") {
      imageData = `data:image/jpg;base64,${resp.data}`;
    }
    url.value.push(imageData);
    showImageViewer.value = true;
  } catch (error) {
    if (error.response && error.response.status === 404) {
      this.error = "Image not found";
    } else {
      this.error = "Error loading image";
    }
  }
};
const close = () => {
  //必须要这个事件 不然点击右上角关闭按钮没有反应
  showImageViewer.value = false;
  url.value = [];
};

const show = (row) => {
  if (row.tag == "txt") {
    openHandler(row);
  } else if (row.tag == "jpg" || row.tag == "png" || row.tag == "jpeg") {
    showImg(row);
  }
};

let maskObj = shallowReactive({
  flag: false,
  url: "",
});

const formData = ref({
  ybsjid: 0,
  symc: "",
  sysj: new Date(),
  sywcr: "",
  sywj: "",
});
let lineCount = 0;

// txt预览
const openHandler = async (row) => {
  let fileName = row.url.slice(13);

  formData.value = {
    ybsjid: 0,
    symc: fileName,
    sysj: new Date(),
    sywcr: "",
    sywj: "",
  };
  let result = await getFileLineCount(formData.value);
  console.log(formData.value);
  // let result=await getFileLineCount({Symc: fileName})
  lineCount = result.data.total;
  // (maskObj.url = "http://192.168.2.52/api/" + row.url), //服务器地址
  (maskObj.url = "http://202.117.36.39/api/" + row.url), //服务器地址
    // (maskObj.url = "http://localhost:8088/" + row.url), //本地地址
    (maskObj.flag = true);
};

const closeHandler = () => {
  maskObj.url = ""; //清空值
  maskObj.flag = false;
};

const created = (row) => {};
</script>
<style scoped>
.name {
  cursor: pointer;
}

.upload-btn + .upload-btn {
  margin-left: 12px;
}

.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

.gva-crumb {
  margin-left: 10px;
}

.blue-underline {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}
</style>